# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2019/11/3 20:08
# @Author  : wenjxu
# @Email   : wenjxususu@163.com
# @File    : utils.py
# @Software: PyCharm

import json, traceback, os, io, yaml, re
from urllib.parse import unquote, urlparse


def loads_json(file_path):
    '''
    loads Har to harTocase
    '''

    try:
        with open(file_path, encoding="utf-8", mode="r") as f:
            handler_data = f.read().lstrip("﻿").strip()
            data = json.loads(handler_data)
            return data
    except Exception:
        traceback.print_exc()


def convert_list_to_dict(list):
    return {
        item["name"]: item["value"] for item in list
    }


def convert_x_www_form_urlencoded_to_dict(post_data):
    '''

    Args:
        post_data (str): a=1&b=2

    Returns:
        dict: {"a":1, "b":2}
    '''

    if isinstance(post_data, str):
        converted_dict = {}
        for k_v in post_data.split("&"):
            try:
                key, value = k_v.split("=")
            except ValueError:
                raise Exception(
                    "Invalid x_www_form_urlencoded data format: {}".format(post_data)
                )
            converted_dict[key] = unquote(value)
        return converted_dict
    else:
        return post_data


def convert_form_data_to_dict(post_data):
    '''
    Returns:
        converted_dict: {"a":1, "b":2 , "files": {"file":${get_file(file_path)}}}
    '''
    converted_dict = {}

    if isinstance(post_data, str):
        common_pattern_data = re.findall('form-data;.*name="\w+"\r\n\r\n.*\r\n', post_data)
        file_pattern_data = re.findall('form-data; name="(.*)"; filename', post_data)

        for common_data in common_pattern_data:
            k = re.findall('="(.*)"', common_data)[0]
            v = re.findall("\r\n\r\n(.*)\r\n", common_data)[0]
            converted_dict[k] = v

        over_dict = {}
        for file_key in file_pattern_data:
            over_dict[file_key] = '${get_file(file_path)}'
        converted_dict["files"] = over_dict

        return converted_dict
    else:
        return post_data


def convert_dict_to_list(post_data):
    return [{i: v} for i, v in post_data.items()]


def convert_url_parse_to_domain(url):
    # test_url = 'http://test.baletoo.com/Admin/AgencyHouse/uploadHousePhoto.html'
    parsed = urlparse(url)
    domain = parsed.scheme + r"://" + parsed.netloc
    return domain


def convert_url_parse_to_path(url):
    # test_url = 'http://test.baletoo.com/Admin/AgencyHouse/uploadHousePhoto.html'
    return urlparse(url).path


def convert_value_to_variable(data_dict):
    '''
    Args:
        data_dict (dict): {'v': '3.9.0', 'version_code': '390'}

    Returns:
        dict : {'v': "$v", 'version_code': '$version_code'}
    '''
    for k, v in data_dict.items():
        data_dict[k] = "${}".format(k)

    return data_dict


def dump_yamlfile(data, filename):
    with io.open(filename, mode="w", encoding="utf-8") as outfile:
        yaml.dump(data, outfile, allow_unicode=True, default_flow_style=False, indent=4, sort_keys=False)


def dump_jsonfile(data, filename):
    with io.open(filename, mode="w", encoding="utf-8") as outfile:
        my_json_str = json.dumps(data, ensure_ascii=False, indent=4, sort_keys=False)
        outfile.write(my_json_str)


def loads_yamlfile(filename):
    yaml.warnings({'YAMLLoadWarning': False})
    with io.open(filename, mode="r", encoding="utf-8") as outfile:
        for data in yaml.load_all(outfile.read()):
            print(data)


BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
demo_urlencoded = os.path.join(BASE_DIR, "core/harTocase/tests/data/demo_urlencoded.har")
demo_quickstart = os.path.join(BASE_DIR, "core/harTocase/tests/data/demo_application_json.har")
demo_formdata = os.path.join(BASE_DIR, "core/harTocase/tests/data/demo_formdata.har")
baletu_form_data = os.path.join(BASE_DIR, "core/harTocase/tests/data/baletu_form_data.har")
docreate_data = os.path.join(BASE_DIR, "core/harTocase/tests/data/docreate.har")
demo_text_html = os.path.join(BASE_DIR, "core/harTocase/tests/data/demo_text_html.har")
demo = os.path.join(BASE_DIR, "core/harTocase/tests/data/demo.har")

if __name__ == '__main__':
    pass
